/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package socof.wget;

import Downloader.CoreDownloader;
import java.io.IOException;
import java.util.logging.Level;
import java.util.logging.Logger;

/**
 *
 * @author Carlos Pinheiro
 */
public class ExecutorDownloader implements Runnable
{

    private ResizeableSemaphore rs;

    public ExecutorDownloader(ResizeableSemaphore sem) throws InterruptedException
    {
        this.rs = sem;
        this.rs.acquire();
    }

    @Override
    public void run()
    {
        WebResource wr = PendingQueue.getInstance().poll();
        if (wr == null)
        {
            return;
        }

        String sUrl = wr.getSourceUrl().toString();
        String localPath = wr.getLocalPath();
        System.out.println("Downloading " + sUrl + " ...");
        try
        {

            CoreDownloader d = new CoreDownloader();
            d.coreDownloadFile(sUrl, localPath, 100);
            long size = d.getSize();

            if (size > 0)
            {
                BandwithAllocation.getInstance().addDownload(size);
            }

            d.downloadFile();
            wr.setLocalPath(d.getFullLocalPathFile());           
            // TODO Pass html files to parte queue

            if (d.isPagetoParser())
            {
                ToParseQueue.getInstance().offer(wr);
            }


            if (size > 0)
            {
                BandwithAllocation.getInstance().removeDownload(size);
            }

        }
        catch (Exception ex)
        {
            Logger.getLogger(ExecutorDownloader.class.getName()).log(Level.SEVERE, null, ex);
        }

        //BandwithAllocation.getInstance().addDownload(downloading);
        //Thread.sleep(2000);
        //BandwithAllocation.getInstance().removeDownload(downloading);

        System.out.println("Downloaded: " + sUrl + ".");

        this.rs.release();
    }
}
